/**
 * Copyright 2010 Matthew Werny & Burk Price.
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 * http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * under the License.
 */
package net.iceflow.db.jdbc.schema;

import java.sql.Connection;
import java.sql.Driver;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;
import net.iceflow.db.jdbc.DatabaseUtils;

abstract class AbstractSchemaCommand {

    private String driverName;
    private String url;
    private String username;
    private String password;

    public AbstractSchemaCommand(String url, String username, String password) {
        this(DatabaseUtils.driverClass(url), url, username, password);
    }

    public AbstractSchemaCommand(String driver, String url, String username, String password) {
        this.driverName = driver;
        this.url = url;
        this.username = username;
        this.password = password;
    }

    public abstract void execute() throws SQLException, ClassNotFoundException;

    public void execute(String createSql) throws SQLException, ClassNotFoundException {
        String serverUrl = DatabaseUtils.extractServerUrl(url);
        String databaseName = DatabaseUtils.extractDatabaseName(url);

        switch (DatabaseUtils.databaseType(url)) {
            case MYSQL:
                databaseName = "`" + databaseName + "`";
                break;

            case SQL_SERVER:
                break;

            case POSTGRESQL:
                databaseName = "\"" + databaseName + "\"";
                break;
        }

        Driver driver = null;

        try {
            driver = (Driver) Class.forName(this.driverName).newInstance();
        } catch (InstantiationException ex) {
            // Intentionally do nothing, for now
        } catch (IllegalAccessException ex) {
            // Intentionally do nothing, for now
        }

        Properties properties = new Properties();
        properties.put("user", username);
        properties.put("password", password);
        Connection connection = driver.connect(serverUrl, properties);

        try {
            Statement statement = connection.createStatement();
            statement.execute(String.format(createSql, databaseName));
            statement.close();
        } finally {
            connection.close();
        }
    }
}
